package cn.tedu.test.charging.rabbitmq.dx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class DeadLeaterDemo {
    //管理一个连接对象
    private Channel channel;
    @Before
    public void init() throws IOException, TimeoutException {
        //创建一个连接工厂,提供工厂的参数 连接rabbtimq的参数
        ConnectionFactory factory = new ConnectionFactory();
        //rabbitmq-server服务端 ip 与 端口 TCP协议
        factory.setHost("192.168.8.100");
        factory.setPort(5672);
        //提供用户名密码 本地local guest/guest 虚拟机admin/123456
        factory.setUsername("admin");
        factory.setPassword("123456");
        //rabbitmq virtual做数据隔离 连接的虚拟主机不一样,能够使用的交换机 队列 消息 是不同
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        channel= connection.createChannel();
    }
    private static final String BIZ_EXCHANGE="BIZ_EXCHANGE";//模拟业务交换机
    private static final String BIZ_QUEUE="BIZ_QUEUE";//模拟业务队列 本来要有业务消费者,但是案例中不绑定
    //fanout 不指定路由key绑定
    private static final String DL_EXCHANGE="DL_EXCHANGE";//模拟死信交换机
    private static final String DL_QUEUE="DL_QUEUE";//模拟最终死信队列 也是观察结果
    //死信路由key
    private static final String DL_ROUTING_KEY="DL_ROUTING_KEY";
    @Test
    public void declareDeadLeaterComponents() throws IOException {
        //4个组件 3个绑定 1个绑定是通过queue的属性设置的
        channel.exchangeDeclare(BIZ_EXCHANGE,"fanout",true,false,null);
        channel.exchangeDeclare(DL_EXCHANGE,"direct",true,false,null);
        channel.queueDeclare(DL_QUEUE,true,false,false,null);
        //业务队列要使用3个属性 x-message-ttl dead-leater-ex dead-leater-rk
        Map<String,Object> args=new HashMap<>();
        args.put("x-message-ttl",10000);//超时10秒钟
        args.put("x-dead-letter-exchange",DL_EXCHANGE);//死信队列去向
        args.put("x-dead-letter-routing-key",DL_ROUTING_KEY);
        channel.queueDeclare(BIZ_QUEUE,true,false,false,args);
        //两组组件之间的绑定关系
        channel.queueBind(BIZ_QUEUE,BIZ_EXCHANGE,"");
        channel.queueBind(DL_QUEUE,DL_EXCHANGE,DL_ROUTING_KEY);
    }
}
